package org.zjt.chapter1.promise;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-12-04 3:33 PM
 * @see
 */
public class PromiseClient {

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);

        ChannelFuture channelFuture = new Bootstrap().group(eventExecutors).channel(NioSocketChannel.class).handler(new SimpleChannelInboundHandler<ByteBuf>() {
            @Override
            protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                byte[] bytes = new byte[msg.readableBytes()];
                msg.readBytes(bytes);
                String str = new String(bytes);
                System.out.println(str);


                DefaultPromise<String> stringDefaultPromise = new DefaultPromise<>(ctx.executor());

                new Thread(() -> {
                    try {
                        Thread.sleep(5 * 1000);
                        stringDefaultPromise.setSuccess("785438578435834543");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        stringDefaultPromise.setFailure(e);
                    }
                }).start();


                stringDefaultPromise.addListener((GenericFutureListener<Future<String>>)
                        future -> ctx.writeAndFlush(Unpooled.wrappedBuffer(future.get().getBytes())));


            }
        }).connect("localhost", 9090);


        channelFuture.channel().writeAndFlush(Unpooled.wrappedBuffer("ssdsdss".getBytes()));

        channelFuture.channel().closeFuture().sync();

        eventExecutors.shutdownGracefully();
    }
}
